import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/server_config.dart';
import 'log_service.dart';

class SubscriptionService {
  final LogService _logService = LogService();
  
  Future<List<ServerConfig>> fetchServers(String subscriptionUrl) async {
    try {
      _logService.info('Fetching subscription from URL...', category: 'subscription');
      final response = await http.get(Uri.parse(subscriptionUrl));
      
      if (response.statusCode != 200) {
        _logService.error('Failed to fetch subscription: HTTP ${response.statusCode}', category: 'subscription');
        throw Exception('Failed to fetch subscription: HTTP ${response.statusCode}');
      }

      // 尝试解码内容 - 先尝试 base64，如果失败则使用纯文本
      String content;
      try {
        // 某些订阅（如标准的 v2ray 订阅）返回 base64 编码的内容
        content = utf8.decode(base64.decode(response.body));
        _logService.debug('Successfully decoded base64 subscription content', category: 'subscription');
        print('✅ Successfully decoded base64 subscription content');
      } catch (e) {
        // 某些订阅（如 GitLab raw 文件）直接返回纯文本
        content = response.body;
        _logService.debug('Using plain text subscription content (not base64 encoded)', category: 'subscription');
        print('✅ Using plain text subscription content (not base64 encoded)');
      }
      
      // Parse server links (vmess://, vless://, trojan://, ss://)
      final lines = content.split('\n');
      final servers = <ServerConfig>[];
      
      _logService.debug('Parsing ${lines.length} lines from subscription...', category: 'subscription');
      print('📋 Parsing ${lines.length} lines from subscription...');
      
      for (var line in lines) {
        line = line.trim();
        if (line.isEmpty) continue;
        
        try {
          if (line.startsWith('vmess://')) {
            servers.add(parseVMessLink(line));
          } else if (line.startsWith('vless://')) {
            servers.add(parseVLessLink(line));
          } else if (line.startsWith('trojan://')) {
            servers.add(parseTrojanLink(line));
          } else if (line.startsWith('ss://')) {
            servers.add(parseShadowsocksLink(line));
          } else {
            // 忽略不支持的协议
            if (line.length > 10) {
              print('⚠️ Unsupported protocol in line: ${line.substring(0, 20)}...');
            }
          }
        } catch (e) {
          _logService.warning('Failed to parse server link: $e', category: 'subscription');
          print('❌ Failed to parse server link: $e');
        }
      }
      
      _logService.info('Successfully parsed ${servers.length} servers from subscription', category: 'subscription');
      print('✅ Successfully parsed ${servers.length} servers from subscription');
      return servers;
    } catch (e) {
      _logService.error('Error fetching subscription: $e', category: 'subscription');
      print('❌ Error fetching subscription: $e');
      rethrow;
    }
  }

  String _generateUniqueId() {
    // 生成唯一ID：时间戳 + 随机数，确保即使在同一毫秒创建多个服务器也不会重复
    final timestamp = DateTime.now().microsecondsSinceEpoch;
    final random = (timestamp * 31) % 1000000; // 使用简单的伪随机
    return '${timestamp}_$random';
  }

  ServerConfig parseVMessLink(String link) {
    try {
      print('🔍 Parsing VMess link...');
      print('   Link length: ${link.length}');
      
      // vmess://base64encodedconfig
      final base64Part = link.substring(8);
      print('   Base64 part length: ${base64Part.length}');
      
      final decodedBytes = base64.decode(base64Part);
      final decodedStr = utf8.decode(decodedBytes);
      print('   Decoded JSON: $decodedStr');
      
      final config = json.decode(decodedStr);
      print('   Config keys: ${config.keys.toList()}');
      
      final server = ServerConfig(
        id: _generateUniqueId(),
        name: config['ps'] ?? 'VMess Server',
        protocol: 'vmess',
        address: config['add'] ?? '',
        port: int.tryParse(config['port']?.toString() ?? '443') ?? 443,
        userId: config['id'] ?? '',
        alterId: config['aid']?.toString() ?? '0',
        security: config['scy'] ?? 'auto',
        network: config['net'] ?? 'tcp',
        path: config['path'],
        host: config['host'],
        tls: config['tls'],
        sni: config['sni'],
      );
      
      print('✅ VMess parsed successfully:');
      print('   Name: ${server.name}');
      print('   Address: ${server.address}:${server.port}');
      print('   Protocol: ${server.protocol}');
      print('   Network: ${server.network}');
      
      return server;
    } catch (e, stackTrace) {
      print('❌ Error parsing VMess link: $e');
      print('   Stack trace: $stackTrace');
      rethrow;
    }
  }

  ServerConfig parseVLessLink(String link) {
    try {
      print('🔍 Parsing VLESS link...');
      print('   Link: ${link.substring(0, link.length > 50 ? 50 : link.length)}...');
      
      // vless://uuid@address:port?params#name
      final uri = Uri.parse(link);
      final params = uri.queryParameters;
      
      print('   Host: ${uri.host}');
      print('   Port: ${uri.port}');
      print('   UserInfo: ${uri.userInfo}');
      print('   Fragment: ${uri.fragment}');
      print('   Params: ${params.keys.toList()}');
      
      final server = ServerConfig(
        id: _generateUniqueId(),
        name: uri.fragment.isNotEmpty ? Uri.decodeComponent(uri.fragment) : 'VLESS Server',
        protocol: 'vless',
        address: uri.host,
        port: uri.port,
        userId: uri.userInfo,
        security: params['security'] ?? 'none',
        network: params['type'] ?? 'tcp',
        path: params['path'],
        host: params['host'],
        tls: params['security'],
        sni: params['sni'],
        alpn: params['alpn'],
        fingerprint: params['fp'],
      );
      
      print('✅ VLESS parsed successfully:');
      print('   Name: ${server.name}');
      print('   Address: ${server.address}:${server.port}');
      
      return server;
    } catch (e, stackTrace) {
      print('❌ Error parsing VLESS link: $e');
      print('   Stack trace: $stackTrace');
      rethrow;
    }
  }

  ServerConfig parseTrojanLink(String link) {
    try {
      print('🔍 Parsing Trojan link...');
      
      // trojan://password@address:port?params#name
      final uri = Uri.parse(link);
      final params = uri.queryParameters;
      
      print('   Host: ${uri.host}');
      print('   Port: ${uri.port}');
      print('   Fragment: ${uri.fragment}');
      
      final server = ServerConfig(
        id: _generateUniqueId(),
        name: uri.fragment.isNotEmpty ? Uri.decodeComponent(uri.fragment) : 'Trojan Server',
        protocol: 'trojan',
        address: uri.host,
        port: uri.port,
        userId: uri.userInfo,
        security: params['security'] ?? 'tls',
        network: params['type'] ?? 'tcp',
        path: params['path'],
        host: params['host'],
        tls: params['security'],
        sni: params['sni'],
        alpn: params['alpn'],
        fingerprint: params['fp'],
      );
      
      print('✅ Trojan parsed successfully: ${server.name}');
      return server;
    } catch (e, stackTrace) {
      print('❌ Error parsing Trojan link: $e');
      print('   Stack trace: $stackTrace');
      rethrow;
    }
  }

  ServerConfig parseShadowsocksLink(String link) {
    try {
      print('🔍 Parsing Shadowsocks link...');
      
      // ss://base64(method:password)@address:port#name
      final uri = Uri.parse(link);
      
      print('   Host: ${uri.host}');
      print('   Port: ${uri.port}');
      print('   UserInfo: ${uri.userInfo.substring(0, uri.userInfo.length > 20 ? 20 : uri.userInfo.length)}...');
      
      String userInfo;
      if (uri.userInfo.contains(':')) {
        userInfo = uri.userInfo;
      } else {
        userInfo = utf8.decode(base64.decode(uri.userInfo));
      }
      
      final parts = userInfo.split(':');
      print('   Method: ${parts[0]}');
      
      final server = ServerConfig(
        id: _generateUniqueId(),
        name: uri.fragment.isNotEmpty ? Uri.decodeComponent(uri.fragment) : 'Shadowsocks Server',
        protocol: 'shadowsocks',
        address: uri.host,
        port: uri.port,
        userId: parts.length > 1 ? parts[1] : '',
        security: parts[0],
      );
      
      print('✅ Shadowsocks parsed successfully: ${server.name}');
      return server;
    } catch (e, stackTrace) {
      print('❌ Error parsing Shadowsocks link: $e');
      print('   Stack trace: $stackTrace');
      rethrow;
    }
  }
}
